//microcommand define -lnn-pjsk-chibi-circle-test
const { pathToFileURL } = require("url")

inject(["puppeteer"])

const cache = Object.create(null)
const cacheDuration = 600_000

async function getCached(url) {
  const now = Date.now()
  const cached = cache[url]

  if (cached && cached.expiry > now) return cached.data

  const headers = {}
  if (cached && cached.lastModified) headers["If-Modified-Since"] = cached.lastModified

  try {
    const response = await ctx.http(url, {
      headers,
      validateStatus: status => status === 200 || status === 304,
    })

    if (response.status === 304) {
      cache[url].expiry = now + cacheDuration
      return cached.data
    }

    const lastModified = response.headers["last-modified"]
    cache[url] = {
      data: response.data,
      expiry: now + cacheDuration,
      lastModified,
    }
    return response.data
  } catch (error) {
    if (!cached) throw error
    ctx.logger.warn(error)
    return cached.data
  }
}

signature("<gcuid:posint>", { hidden: true, slash: false })
action(async ({ session }, gcuid) => {
  const gcuList = await getCached("https://sekai-world.github.io/sekai-master-db-cn-diff/gameCharacterUnits.json")
  const gcu = gcuList.find(o => o.id === gcuid)
  let bg
  if (gcu.id === gcu.gameCharacterId) {
    bg = gcu.colorCode
  } else {
    const charColor = gcuList.find(o => o.id === gcu.gameCharacterId).colorCode
    const plcList = await getCached("https://sekai-world.github.io/sekai-master-db-diff/penlightColors.json")
    const unitColor = plcList.find(o => !o.characterId && o.unit === gcu.unit).colorCode
    bg = `radial-gradient(circle closest-side, ${unitColor} 80%, ${charColor} 80%)`
  }
  return ctx.puppeteer.render(
    `<img src="${pathToFileURL(`/root/why/croppedChibis/${gcuid}.png`).href}" style="width: 70px; border-radius: 50%; background: ${bg}">`,
    async page => h.image(await page.screenshot({ clip: await (await page.$("img")).boundingBox(), omitBackground: true }), "image/png"),
  )
})